package net.ecpt.clm.services;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.ExcelPoiUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javolution.util.FastList;
import javolution.util.FastMap;

public class ClmPaymentOrderXlsServices {
    public static final String module = ClmCollectionOrderXlsServices.class.getName();

    /**
     * 导入
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> importXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Delegator delegator = dctx.getDelegator();
	List<String> messageList = new ArrayList<String>();
	List<Map<String, Object>> sheetList = (List<Map<String, Object>>) context.get("sheetList");
	try {
	    int i = 0;

	    for (Map<String, Object> row : sheetList) {
		i = i + 1;
		String paymentCode = ExcelPoiUtils.getCellString(row, 0);
		String userLoginId = ExcelPoiUtils.getCellString(row, 1);
		String paymentTypeDetailId = ExcelPoiUtils.getCellString(row, 2);
		String costCodeName = ExcelPoiUtils.getCellString(row, 3);
		String project = ExcelPoiUtils.getCellString(row, 4);
		String agreementCode = ExcelPoiUtils.getCellString(row, 5);
		Timestamp expectPaymentDate = ExcelPoiUtils.getCellTimestamp(row, 6);
		String corpcode = ExcelPoiUtils.getCellString(row, 7);
		String collectionCard = ExcelPoiUtils.getCellString(row, 8);
		String collectionName = ExcelPoiUtils.getCellString(row, 9);
		String isadvance = ExcelPoiUtils.getCellString(row, 10);

		String scomment = ExcelPoiUtils.getCellString(row, 11);
		String supplier = ExcelPoiUtils.getCellString(row, 12);
		BigDecimal quantity = ExcelPoiUtils.getCellBigDecimal(row, 13);
		BigDecimal money = ExcelPoiUtils.getCellBigDecimal(row, 14);
		BigDecimal notaxmoney = ExcelPoiUtils.getCellBigDecimal(row, 15);
		String taxcodeid = ExcelPoiUtils.getCellString(row, 16);
		Timestamp paymentdate = ExcelPoiUtils.getCellTimestamp(row, 17);
		String remark = ExcelPoiUtils.getCellString(row, 18);
		String costproject = ExcelPoiUtils.getCellString(row, 29);

		// 判断
		if (UtilValidate.isEmpty(paymentCode)) {
		    messageList.add("第" + (i + 1) + "行,付款编号不能为空。");
		    continue;
		}
		if (UtilValidate.isNotEmpty(userLoginId)) {
		    if (UtilValidate.isEmpty(paymentTypeDetailId)) {
			messageList.add("第" + (i + 1) + "行,付款类型不能为空。");
			continue;
		    }

		    if (UtilValidate.isEmpty(costCodeName)) {
			messageList.add("第" + (i + 1) + "行,成本中心不能为空。");
			continue;
		    }
		    if (UtilValidate.isEmpty(project)) {
			messageList.add("第" + (i + 1) + "行,所属项目不能为空。");
			continue;
		    }
		    if (UtilValidate.isEmpty(agreementCode)) {
			messageList.add("第" + (i + 1) + "行,所属合同不能为空。");
			continue;
		    }
		    if (UtilValidate.isEmpty(collectionCard)) {
			messageList.add("第" + (i + 1) + "行,收款帐号不能为空。");
			continue;
		    }
		    if (UtilValidate.isEmpty(collectionName)) {
			messageList.add("第" + (i + 1) + "行,开户行名称不能为空。");
			continue;
		    }
		    if (UtilValidate.isEmpty(isadvance)) {
			messageList.add("第" + (i + 1) + "行,是否预付款不能为空。");
			continue;
		    }
		}

		if (UtilValidate.isEmpty(supplier)) {
		    messageList.add("第" + (i + 1) + "行,供应商不能为空。");
		    continue;
		}
		
		if (UtilValidate.isEmpty(quantity)) {
		    messageList.add("第" + (i + 1) + "行,数量不能为空。");
		    continue;
		}
		if (UtilValidate.isEmpty(money)) {
		    messageList.add("第" + (i + 1) + "行,金额不能为空。");
		    continue;
		}
		if (UtilValidate.isEmpty(notaxmoney)) {
		    messageList.add("第" + (i + 1) + "行,无税金额类型不能为空。");
		    continue;
		}
		if (UtilValidate.isEmpty(taxcodeid)) {
		    messageList.add("第" + (i + 1) + "行,税码不能为空。");
		    continue;
		}
		if (UtilValidate.isEmpty(paymentdate)) {
		    messageList.add("第" + (i + 1) + "行,付款日期不能为空。");
		    continue;
		}
		
		
		String isSyncNc = "N";
		GenericValue entity = null;
		String id = "";
		// 此处加个例子,比如这里需要先创建人员
		String isOk = "N";
		String isCreate = "N";
		JSONArray array = new JSONArray();
		if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isNotEmpty(paymentTypeDetailId)) {
		    isOk = "Y";
		}
		List<GenericValue> entityList = delegator.findByAnd("ClmPaymentOrder",
			UtilMisc.toMap("paymentCode", paymentCode), null, false);
		if (UtilValidate.isEmpty(entityList)) {
		    id = delegator.getNextSeqId("ClmPaymentOrder");
		    entity = delegator.makeValue("ClmPaymentOrder", UtilMisc.toMap("id", id));
		    isCreate = "Y";
		} else {
		    entity = EntityUtil.getFirst(entityList);
		    id = EntityUtil.getFirst(entityList).getString("id");
		    isSyncNc = entity.getString("isSyncNc");
		}
		if (isOk.equals("Y")) {
		    GenericValue agreement = EntityUtil.getFirst(delegator.findByAnd("ClmAgreement", UtilMisc.toMap("agreementCode", agreementCode),
			    null,false));
		    if (UtilValidate.isEmpty(agreement)) {
			messageList.add("第" + (i + 1) + "行,系统合同编号不存在。");
			continue;
		    }

		    GenericValue user = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", userLoginId),
			    false);
		    if (UtilValidate.isEmpty(user)) {
			messageList.add("第" + (i + 1) + "行,提交人在系统中不存在。");
			continue;
		    }
		    
		    String paymentCompany = getDataDictionarySeq(delegator, "COSTPAYMENT_TYPE", corpcode);
		    if(UtilValidate.isEmpty(paymentCompany)) {
			messageList.add("第" + (i + 1) + "行,财务组织编号在系统中不存在。");
			continue;
		    }
		    
		    List<GenericValue> departList = delegator.findByAnd("DataDictionary",
			    UtilMisc.toMap("description", costCodeName,"dictionaryTypeId","COSTCENTER_TYPE"), null, false);
		    if (UtilValidate.isEmpty(departList)) {
			messageList.add("第" + (i + 1) + "行,部门中心在系统中不存在。");
			continue;
		    }
		    String costCode = EntityUtil.getFirst(departList).getString("dictionaryCode");
		    String paymentTypeDetailIdInfo = ExcelPoiUtils.getDataDictionaryCode(delegator, "PAYMENTORDER_TYPE",
			    paymentTypeDetailId);
		    String partyId = user.getString("partyId");

		    entity.set("statusId", "0");
		    entity.set("paymentTypeId", "0");
		    entity.set("paymentCompany", paymentCompany);
		    entity.set("partyId", partyId);
		    entity.set("paymentCode", paymentCode); // 收款编号
		    entity.set("isSyncNc", isSyncNc);
		    entity.set("paymentTypeDetailId", paymentTypeDetailIdInfo);
		    entity.set("costCode", costCode);
		    entity.set("project", project);
		    entity.set("agreementId", agreement.getString("id"));
		    entity.set("agreementCode", agreementCode);
		    entity.set("expectPaymentDate", expectPaymentDate);
		    entity.set("corpcode", corpcode);

		    entity.set("collectionCard", collectionCard);
		    entity.set("collectionName", collectionName);
		    entity.set("isadvance", isadvance);
		    
		    
		    entity.set("itemList", "");
		    if (isCreate.equals("Y")) {
			entity.create();
		    } else {
			entity.store();
		    }
		}else {
		    //说明非主数据.且编号不存在.
		    if (isCreate.equals("Y")) {
			continue;
		    }
		}

		array = JSONArray.parseArray(entity.getString("itemList"));
		if (UtilValidate.isEmpty(array))
		    array = new JSONArray();
		JSONObject ob1 = new JSONObject();

		ob1.put("scomment", scomment);// 摘要
		ob1.put("objtype", "1"); // 往来对象
		ob1.put("supplier", supplier);// 客户
		ob1.put("quantity", quantity);
		ob1.put("money", money); // 金额
		ob1.put("notaxmoney", notaxmoney);
		ob1.put("taxcodeid", taxcodeid);
		ob1.put("paymentdate", paymentdate);
		ob1.put("remark", remark);
		ob1.put("costproject", costproject);
		array.add(ob1);
		entity.set("itemList", array.toString());
		entity.store();
	    }
	    result.put("messageList", messageList);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }
    
    public static String getDataDictionarySeq(Delegator delegator, String dictionaryTypeId, String sequenceId)
	    throws GenericEntityException {
	String result = "";
	if (UtilValidate.isEmpty(sequenceId)) {
	    return result;
	}
	List<GenericValue> values = delegator.findByAnd("DataDictionary",
		UtilMisc.toMap("dictionaryTypeId", dictionaryTypeId, "sequenceId", sequenceId), null, true);
	GenericValue dataDictionary = EntityUtil.getFirst(values);
	if (UtilValidate.isNotEmpty(dataDictionary)) {
	    result = dataDictionary.getString("dictionaryCode");
	}
	return result;
    }
    
    /**
     * 导出
     */

    public static Map<String, Object> exportXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	String ids = (String) context.get("ids");
	List<String> baseIdList = FastList.newInstance();
	if (UtilValidate.isNotEmpty(ids)) {
	    baseIdList = Arrays.asList(ids.split(";"));
	}
	Map<String, Object> result = ServiceUtil.returnSuccess();

	EntityCondition mainCond = null;
	List<EntityCondition> andExprs = FastList.newInstance();
	if (UtilValidate.isNotEmpty(baseIdList))
	    andExprs.add(EntityCondition.makeCondition("id", EntityOperator.IN, baseIdList));
	if (andExprs.size() > 0)
	    mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);

	try {
	    List<GenericValue> entityList = delegator.findList("ClmPaymentOrder", mainCond, null, null, null, true);

	    List<Map<String, Object>> list = FastList.newInstance();
	    Map<String, Object> keyMap = FastMap.newInstance();
	    Map<String, Object> keyItemMap = FastMap.newInstance();

	    keyMap.put("0", "paymentCode");
	    keyMap.put("1", "userLoginId");
	    keyMap.put("2", "paymentTypeDetailId");
	    keyMap.put("3", "costCodeName");
	    keyMap.put("4", "project");
	    keyMap.put("5", "agreementCode");
	    keyMap.put("6", "expectPaymentDate");
	    keyMap.put("7", "corpcode");
	    keyMap.put("8", "collectionCard");
	    keyMap.put("9", "collectionName");
	    keyMap.put("10", "isadvance");

	    keyItemMap.put("11", "scomment");
	    keyItemMap.put("12", "supplier");
	    keyItemMap.put("13", "quantity");
	    keyItemMap.put("14", "money");
	    keyItemMap.put("15", "notaxmoney");
	    keyItemMap.put("16", "taxcodeid");
	    keyItemMap.put("17", "paymentdate");
	    keyItemMap.put("18", "remark");
	    keyItemMap.put("19", "costproject");
	    
	    String headers = "付款编号,提交人,付款类型,成本中心,所属项目,系统合同编号,单据日期,财务组织,收款帐号,开户行名称,是否预付款,摘要,供应商,数量,金额,无税金额,税码编号,付款时间,备注说明,费用项目";
	    result.put("headers", headers);

	    for (GenericValue entity : entityList) {
		Map<String, Object> map = FastMap.newInstance();
		String partyId = entity.getString("partyId");
		String corpcode = entity.getString("corpcode");
		List<GenericValue> userList = delegator.findByAnd("UserLogin", UtilMisc.toMap("partyId", partyId), null,
			false);
		String costCode = entity.getString("costCode");
		List<GenericValue> departList = delegator.findByAnd("DataDictionary",
			UtilMisc.toMap("dictionaryCode", costCode,"dictionaryTypeId","COSTCENTER_TYPE"), null, false);

		String paymentTypeDetailId = ExcelPoiUtils.getDataDictionaryDescription(delegator, "PAYMENTORDER_TYPE",
			entity.getString("paymentTypeDetailId"));
		String userLoginId = EntityUtil.getFirst(userList).getString("userLoginId");
		String paymentCode = entity.getString("paymentCode");
		String costCodeName = EntityUtil.getFirst(departList).getString("description");
		String project = entity.getString("project");
		String agreementCode = entity.getString("agreementCode");
		Timestamp expectPaymentDate = entity.getTimestamp("expectPaymentDate");
		String collectionCard = entity.getString("collectionCard");
		String collectionName = entity.getString("collectionName");
		String isadvance = entity.getString("isadvance");

		map.put("paymentCode", paymentCode);
		map.put("userLoginId", userLoginId);
		map.put("paymentTypeDetailId", paymentTypeDetailId);
		map.put("costCodeName", costCodeName);
		map.put("project", project);
		map.put("agreementCode", agreementCode);
		map.put("expectPaymentDate", expectPaymentDate);
		map.put("corpcode", corpcode);
		map.put("collectionCard", collectionCard);
		map.put("collectionName", collectionName);
		map.put("isadvance", isadvance);
		
		
		
		
		JSONArray entityItemList = new JSONArray();
		if (UtilValidate.isNotEmpty(entity.getString("itemList"))) {
		    entityItemList = JSONArray.parseArray(entity.getString("itemList"));
		}
		List<Map<String, Object>> itemList = FastList.newInstance();
		for (Object item : entityItemList) {
		    JSONObject itemInfo = (JSONObject) item;
		    Map<String, Object> itemMap = FastMap.newInstance();

		    String scomment = itemInfo.getString("scomment");
		    String supplier = itemInfo.getString("supplier");
		    BigDecimal quantity = itemInfo.getBigDecimal("quantity");
		    BigDecimal money = itemInfo.getBigDecimal("money");
		    BigDecimal notaxmoney = itemInfo.getBigDecimal("notaxmoney");
		    String taxcodeid = itemInfo.getString("taxcodeid");
		    Timestamp paymentdate = itemInfo.getTimestamp("paymentdate");
		    String remark = itemInfo.getString("remark");
		    String costproject = itemInfo.getString("costproject");
		    
		    itemMap.put("scomment", scomment);
		    itemMap.put("supplier", supplier);
		    itemMap.put("quantity", quantity);
		    itemMap.put("money", money);
		    itemMap.put("notaxmoney", notaxmoney);
		    itemMap.put("taxcodeid", taxcodeid);
		    itemMap.put("paymentdate", paymentdate);
		    itemMap.put("remark", remark);
		    itemMap.put("costproject", costproject);
		    itemList.add(itemMap);
		}

		map.put("itemList", itemList);
		list.add(map);
	    }
	    result.put("list", list);
	    result.put("keyMap", keyMap);
	    result.put("keyItemMap", keyItemMap);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

}
